#! /bin/usr/env bash

[ -f "$HOME/.profile_local" ] && source "$HOME/.profile_local"

export EDITOR=nvim

# ------------------------------------------------------------------------------
# XDG
# ------------------------------------------------------------------------------

if [ -z "$DOTFILES" ] && [ -d "$HOME/projects/dotfiles" ]; then
    DOTFILES=$HOME/projects/dotfiles
fi

if [ -n "$DOTFILES" ]; then
    export XDG_CONFIG_HOME="$DOTFILES/config"
else
    echo "DOTFILES is not defined"
fi

if [ -z "$XDG_BASE" ]; then
    echo "Warning: XDG_BASE is not defined, using $HOME"
    XDG_BASE=$HOME
fi

export XDG_CACHE_HOME="$XDG_BASE/.cache"
export XDG_DATA_HOME="$XDG_BASE/.data"
# export XDG_RUNTIME_DIR="$XDG_BASE/.runtime"

# [ -d "$XDG_RUNTIME_DIR" ] || mkdir "$XDG_RUNTIME_DIR"
[ -d "$XDG_CACHE_HOME"  ] || mkdir "$XDG_CACHE_HOME"
[ -d "$XDG_DATA_HOME"   ] || mkdir "$XDG_DATA_HOME"

export PYLINTHOME="$XDG_CACHE_HOME/pylint"
export PYTHON_EGG_CACHE="$XDG_CACHE_HOME/python-eggs"

export TMUX_TMPDIR="$XDG_RUNTIME_DIR/tmux"

export INPUTRC="$XDG_CONFIG_HOME/readline/inputrc"
export NPM_CONFIG_USERCONFIG=$XDG_CONFIG_HOME/npm/npmrc
export RIPGREP_CONFIG_PATH=$XDG_CONFIG_HOME/ripgreprc

export CARGO_HOME="$XDG_DATA_HOME/cargo"
export RLWRAP_HOME="$XDG_DATA_HOME/rlwrap"

# ------------------------------------------------------------------------------
# Homebrew
# ------------------------------------------------------------------------------

export HOMEBREW_CACHE="$XDG_CACHE_HOME"

# ------------------------------------------------------------------------------
# Misc
# ------------------------------------------------------------------------------

if [ -z "$BREW_PREFIX" ] && [ -d /opt/homebrew ]; then
    BREW_PREFIX=/opt/homebrew
fi

if [ -n "$BREW_PREFIX" ]; then
  COREUTILS_PATH="$BREW_PREFIX/opt/coreutils/libexec"
  [ -d "$COREUTILS_PATH/gnubin" ] && PATH="$COREUTILS_PATH/gnubin:$PATH"
  [ -d "$COREUTILS_PATH/gnuman" ] && MANPATH="$COREUTILS_PATH/gnuman:$MANPATH"

  MAKE_PATH="$BREW_PREFIX/opt/make/libexec/gnubin"
  [ -d "$MAKE_PATH" ] && PATH="$MAKE_PATH:$PATH"
fi

for i in \
    "$HOME" \
    "$DOTFILES" \
    "/opt/homebrew" \
    "$HOME/.luarocks" \
    "$HOME/.local" \
    "$XDG_DATA_HOME/npm" \
    "$XDG_DATA_HOME/cargo"
do
    [ -d "$i/bin"       ] && PATH="$i/bin:$PATH"
    [ -d "$i/man"       ] && MANPATH="$i/man:$MANPATH"
    [ -d "$i/share/man" ] && MANPATH="$i/share/man:$MANPATH"
    [ -d "$i/info"      ] && INFOPATH="$i/info:$INFOPATH"
done
